// Set service path
window.softools = {};
window.softools.servicePath = "https://api.softools.net/";
window.softools.tenant = "demo";
window.softools.token = "";

// Set default headers
var setXhrHeaders = function (jqxhr) {
    jqxhr.setRequestHeader("Cache-Control", "no-transform");
    jqxhr.setRequestHeader("X-Softools-Tenant", window.softools.tenant);
    jqxhr.setRequestHeader("Authorization", "Bearer " + window.softools.token);
    jqxhr.setRequestHeader("Content-Type", "application/json");
    jqxhr.setRequestHeader("Accept", "application/json");
}

// Generic function to handle AJAX errors
var handleAjaxError = function (jqxhr, textStatus, errorThrown) {
    if (jqxhr.readyState == 0 || jqxhr.status == 0) {
        return; //Skip this error
    }
    if (jqxhr.status == 401) {
        alert('Not Authorised');
        return;
    }
    if (jqxhr.status == 400) {
        //Chances are that this is due to validation
        return;
    } else {
        try {
            var error = JSON.parse(jqxhr.responseText);
            var displayText = error.Message;
            if (error.ExceptionMessage && error.ExceptionMessage != error.Message) {
                displayText = displayText + " - " + error.ExceptionMessage;
            }
            alert(displayText);
        } catch (e) {
            var displayText = "An unexpected error occurred - " + errorThrown;
            alert(displayText);
        }
    }
}

// Append headers to all requests
$(document).ajaxSend(function (event, jqxhr, settings) {
    setXhrHeaders(jqxhr);
});


$.support.cors = true;


    
function appsViewModel() {
    var self = this;

        self.shouldShowMessage= ko.observable(true); // Message initially visible
    
   //shouldShowMessage: ko.observable(true);

	//OnLoad Event
	//method 1 Main Request
	 self.apps = ko.observableArray([]);
    self.getApps = function () {
	$( ".abc" ).hide();
        var url = window.softools.servicePath + "api/apps";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
            self.apps(ko.mapping.fromJS(data)());
			
        });
    };
	//Other Requests
	//request 1 HomePage
	 self.homepage = ko.observableArray([]);
    self.getHomePage = function () {
        var url = window.softools.servicePath + "Api/Homepages";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
            self.homepage(ko.mapping.fromJS(data)());
			
        });
    };
	//request 2 Full Detail
	 self.fulldetail = ko.observableArray([]);
    self.getFullDetail = function () {
        var url = window.softools.servicePath + "Api/Apps/FullDetails";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
            self.fulldetail(ko.mapping.fromJS(data)());
			
        });
    };
	
	//End Login Request
	
//method 2
self.reportall = ko.observableArray([]);
    self.getAppReportAll = function (asd,abc) {
	$( ".hello" ).visible();

	//alert(abc);
        var url = window.softools.servicePath + "api/apps/pillars/reports/all";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		
            self.reportall(ko.mapping.fromJS(data)());
        });
    };
	
// method 3
	var id;
	var select;
	self.reports11 = ko.observableArray([]);
    self.getAppReport = function (asd,abc) {
	id=asd.Id();
	$( ".hello" ).hide();
	//var abc = ko.observable(abc);  
	//console.log(abc);
	//alert(abc.Identifier._latestValue);
	select=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select+"/reports/"+id;
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reports11(ko.mapping.fromJS(data));
        
		});
		
    };	
	// method 4
	var id1;
	var select1;
	self.reports2 = ko.observableArray([]);
    self.getAppReportField = function (asd,abc) {
	$('#Table1 tr:gt(0)').remove();
	id1=asd.Id();
	//alert(asd.Id());
	select1=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select1+"/Fields";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
			self.reports2(ko.mapping.fromJS(data)());
        
		});
		
    };	
	
	//method 5

	var id5;
	var select5;
	self.reports5 = ko.observableArray([]);
    self.getAppReportFieldAuto = function (asd,abc) {
	id5=asd.Id();
	//alert(asd.Id());
	select5=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select5+"/Fields/WithAutoGenerated";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reports5(ko.mapping.fromJS(data)());
        
		});
		
    };	
	//method 6

	var id6;
	var select6;
	self.reports6 = ko.observableArray([]);
    self.getAppReportFieldId = function (asd,abc) {
		$( ".abc" ).show();
	$('#Table1 tr:gt(0)').remove();
	id6=asd.Id();
	self.shouldShowMessage(false);
	//alert(asd.Id());
	select6=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select6+"/Data/Report/"+id6;
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reports6(ko.mapping.fromJS(data)());
        
		});
		
    };	
	//method 7

	var id7;
	var select7;
	self.reports7 = ko.observableArray([]);
    self.getAppReportIdField = function (asd,abc) {
	//	$( ".abc" ).show();
	//$('#Table1 tr:gt(0)').remove();
	id7=asd.Id();
	//self.shouldShowMessage(false);
	//alert(asd.Id());
	select7=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select6+"/Reports/"+id6+"/Fields";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reports7(ko.mapping.fromJS(data)());
        
		});
		
    };		
	//******************** Start NEW Request ***************************
	//method New 1

	var idchild1;
	var selectchild1;
	self.reportschild1 = ko.observableArray([]);
    self.getAppWithChildApps = function (asd,abc) {
	$('#Table1 tr:gt(0)').remove();
	//idchild1=asd.Id();
        var url = window.softools.servicePath + "api/apps/"+select6+"/WithChildApps";
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		//self.reportschild1(ko.mapping.fromJS(data)());
        
		});
		
    };	
	
	//method New 2

	var idchild2;//need to change
	var selectchild2;//need to change
	self.reportschild2 = ko.observableArray([]);//need to change
    self.getSideApp1 = function (asd,abc) {//need to change
	//alert("AAA");
	//alert(asd.Id());
	$('#Table1 tr:gt(0)').remove();
	idchild2=asd.Id();//need to change
	
	//alert(abc.Id());
	//selectchild1=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select6+"/Forms/GetFormsForAppDataId/"+idchild2;//need to change
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reportschild2(ko.mapping.fromJS(data)());//need to change
        
		});
		
    };	
	
	//method New 3

	var idchild3;//need to change
	var selectchild3;//need to change
	self.reportschild3 = ko.observableArray([]);//need to change
    self.getSideApp3 = function (asd,abc) {//need to change
	//alert("AAA");
	//alert(abc.Id());
	$('#Table1 tr:gt(0)').remove();
	idchild3=abc.Id();//need to change
	
	//alert(abc.Id());
	//selectchild1=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select6+"/Data/"+idchild3+"/Comments/$count";//need to change
        $.ajax(url, {   //Event/Data/53070f7b45870a03ccc809bd/Comments/$count
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reportschild3(ko.mapping.fromJS(data)());//need to change
        
		});
		
    };	
	
		//method New 4

	var idchild4;//need to change
	var selectchild4;//need to change
	self.reportschild4 = ko.observableArray([]);//need to change
    self.getSideApp4 = function (asd,abc) {//need to change
	//alert("AAA");
	//alert(asd.Id());
	$('#Table1 tr:gt(0)').remove();
	idchild4=asd.Id();//need to change
	
	//alert(abc.Id());
	//selectchild1=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select6+"/Fields/WithAutoGenerated";//need to change
        $.ajax(url, {   //Event/Data/53070f7b45870a03ccc809bd/Comments/$count
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reportschild4(ko.mapping.fromJS(data)());//need to change
        
		});
		
    };	
		//method New 5

	var idchild5;//need to change
	var selectchild5;//need to change
	self.reportschild5 = ko.observableArray([]);//need to change
    self.getSideApp5 = function (asd,abc) {//need to change
	//alert("AAA");
	//alert(asd.Id());
	$( ".abc" ).hide();
	$('#Table3 tr:gt(0)').remove();
	idchild5=asd.Id();//need to change
	
	//alert(abc.Id());
	//selectchild1=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select6+"/Data/"+idchild3;//need to change
       var newurl = "https://api.on.softools.net/Account/Login?ReturnUrl=" + "/App/Edit/Event/"+idchild3;
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reportschild5(ko.mapping.fromJS(data));//need to change
		window.open(newurl, '_blank');
		//alert("AA");
		});
	//	console.log(self.reportschild5);
    };	
		//method New 6

	var idchild6;//need to change
	var selectchild6;//need to change
	self.reportschild6 = ko.observableArray([]);//need to change
    self.getSideApp6 = function (asd,abc) {//need to change
	//alert("AAA");
	//alert(asd.Id());
	//$('#Table3 tr:gt(0)').remove();
	idchild6=asd.Id();//need to change
	
	//alert(abc.Id);
	//selectchild1=abc.Identifier._latestValue;
	//alert(select);
        var url = window.softools.servicePath + "api/apps/"+select6+"/Forms/10206";//need to change
        $.ajax(url, {
            type: 'GET',
            beforeSend: setXhrHeaders
        }).done(function (data) {
		self.reportschild6(ko.mapping.fromJS(data));//need to change
        
		});
	//	console.log(self.reportschild5);
    };	
	ko.bindingHandlers.date = {
    init: function (element, valueAccessor, allBindingsAccessor, appsViewModel) {
        try {
		 var val = valueAccessor;
		//alert(val(element.getAttribute('value')));
       // val(element.getAttribute('value'));
		var mydate = Date(val(element.getAttribute('value')))
var value = new Date
            (
                 parseInt(val(element.getAttribute('value')))
            );
		//	alert(value);
var dat = value.getFullYear()+ 
                          
                       "/" + 
           value.getMonth() + 1 + 
                       "/" + 
      value.getDate() ;
//alert(element.currentTarget);
element.setAttribute('value', dat);
        }
        catch (exc) {
        }
        $(element).change(function () {
            var value = valueAccessor();
            value(element.getAttribute('value'));
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor, appsViewModel) {
        var val = valueAccessor;
		//alert(val(element.getAttribute('value')));
       // val(element.getAttribute('value'));
		var mydate = Date(val(element.getAttribute('value')))
var value = new Date
            (
                 parseInt(val(element.getAttribute('value')))
            );
		//	alert(value);
var dat = value.getMonth() + 
                         1 + 
                       "/" + 
           value.getDate() + 
                       "/" + 
       value.getFullYear();
//alert(element.currentTarget);
element.setAttribute('text', dat);
        
    }
};
	//******************** End NEW Request ***************************

	self.filterByLanguage = function(lang) {
	alert(lang.id);
        
    };

	}
	
self.toggleCommentSection = function() {
    self.commentsHidden(!self.commentsHidden());
}
	
	
$(document).ready(function () {
	$( ".abc" ).hide();
	
//alert("RAJ");
   // Auth request
    var authRequest = function (username, password) {
        var url = window.softools.servicePath + "token";

        var auth = {
            grant_type: "password",
            username: window.softools.tenant + "\\" + username,
            password: password
        };

        return $.ajax(url, {
            type: "POST",
            global: false,
            data: auth,
            beforeSend: function (jqxhr) {
                jqxhr.setRequestHeader("Accept", "application/json");
            }
        }).done(function (data) {
            window.softools.token = data.access_token;
			//alert(window.softools.token);
            return true;
        }).fail(function (jqxhr, textStatus, errorThrown) {
            handleAjaxError(jqxhr, textStatus, errorThrown);
            return false;
        });
    }

    authRequest("\jacka", "sunshine1234").then(function (result) {
	
        var model = new appsViewModel();
        model.getApps();
		model.getHomePage();
		model.getFullDetail();
		
        ko.applyBindings(model);
    //var model1 = new appsViewModel();
	//model1.getAppReport();
     // ko.applyBindings(model1);
	 
    
	});
});